package com.xuanyuan.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xuanyuan.domain.AjaxResult;
import com.xuanyuan.entity.Post;
import com.xuanyuan.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;


@Validated
@Controller
@RequestMapping("/api/post")
public class PostController {
    @Autowired
    private PostService postService;

    @ResponseBody
    @RequestMapping("/page")
    public AjaxResult selectPostPage(Post post, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return AjaxResult.success(new PageInfo<>(postService.selectPostList(post)));
    }

    @ResponseBody
    @RequestMapping("/list")
    public AjaxResult selectPostList(Post post) {
        return AjaxResult.success(postService.selectPostList(post));
    }

    @ResponseBody
    @PostMapping("/add")
    public AjaxResult insertPost(@Validated Post post) {
        if (postService.selectPostByName(post.getPostName()) != null) {
            return AjaxResult.error("添加失败，该职位已存在，请换个名字！");
        } else {
            return AjaxResult.toAjax(postService.insertPost(post));
        }
    }

    @ResponseBody
    @PostMapping("/edit")
    public AjaxResult updatePost(@Validated Post post, @NotNull(message = "职位id不能为空") Integer id) {
        //必须需要id
        post.setId(id);
        return AjaxResult.toAjax(postService.updatePost(post));
    }

    @ResponseBody
    @PostMapping("/removes")
    public AjaxResult deletePostByIds(@NotEmpty(message = "职位ids不能为空") String[] ids) {
        return AjaxResult.toAjax(postService.deletePostByIds(ids));
    }
}

